package com.etc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.etc.dao.ProductInfoDao;
import com.etc.entity.ProductInfo;
import com.etc.util.JdbcUtil;

public class ProductInfoDaoImpl implements ProductInfoDao{

	/**
	 * 
	 * 方法作用:查看所有商品信息
	 */
	public List<ProductInfo> findProductInfoAll() {

		List<ProductInfo> list = new ArrayList<ProductInfo>();
		Connection conn = JdbcUtil.getConn();
		String sql = "select id,name,price,stock,img from productinfo ";
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				ProductInfo productInfo = new ProductInfo();
				productInfo.setId(rs.getInt("id"));
				productInfo.setName(rs.getString("name"));
				productInfo.setPrice(rs.getDouble("price"));
				productInfo.setStock(rs.getInt("stock"));
				productInfo.setImg(rs.getString("img"));
				list.add(productInfo);
			}

			JdbcUtil.closeAll(null, ps, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 通过id查看商品信息
	 * @throws SQLException 
	 */
	public ProductInfo findPrductInfoById(Connection conn,int id) throws SQLException{
		String sql = "select * from productinfo where id=? ";
		ResultSet rs = null;
		ProductInfo productInfo = new ProductInfo();
			rs=JdbcUtil.doQuery(conn, sql, id);
			if (rs.next()) {
				productInfo.setId(rs.getInt("id"));
				productInfo.setName(rs.getString("name"));
				productInfo.setPrice(rs.getDouble("price"));
				productInfo.setStock(rs.getInt("stock"));
				productInfo.setImg(rs.getString("img"));
			}
		return productInfo;
		
		
		
		
	}
	/**
	 * 购买成功后更新商品数据
	 * @throws SQLException 
	 */
	public void updateProductInfoById(Connection conn,int id, int count) throws SQLException {
		// TODO Auto-generated method stub
		//count  剩余的库存数量
		    String sql = "update productinfo set stock=? where id=? ";
			JdbcUtil.doUpate(conn, sql, count,id);
	}

	@Override
	public double getPriceByNum(int id, int num) {
		// TODO Auto-generated method stub
		String sql="select price from productinfo where id=?";
		Connection conn=JdbcUtil.getConn();
		ResultSet rs=null;
		double total=0;
		double price=0;
		try {
			rs=JdbcUtil.doQuery(conn, sql, id);
			if(rs.next()){
				price=rs.getDouble("price");
				total=price*num;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return total;
	}
}
